package com.hongyuan.coach.ui.person.view_mode;

import android.app.Application;
import android.graphics.Rect;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.hongyuan.coach.R;
import com.hongyuan.coach.base.CustomViewModel;
import com.hongyuan.coach.base.ItemViewModel;
import com.hongyuan.coach.data.Constants;
import com.hongyuan.coach.data.MyRepository;
import com.hongyuan.coach.data.md5.BaseUtil;
import com.hongyuan.coach.data.userbean.FileBean;
import com.hongyuan.coach.ui.main.beans.ReturnMoreImgBean;
import com.hongyuan.coach.ui.person.activity.CoachDetailsActivity;
import com.hongyuan.coach.ui.person.beans.CoachImgBean;
import com.hongyuan.mvvmhabitx.binding.command.BindingCommand;
import com.hongyuan.mvvmhabitx.bus.event.SingleLiveEvent;
import com.hongyuan.mvvmhabitx.utils.ToastUtils;
import com.luck.picture.lib.entity.LocalMedia;
import com.previewlibrary.enitity.UserViewInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import me.tatarka.bindingcollectionadapter2.BR;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class CoachImgViewModel extends CustomViewModel<MyRepository> {

    //需要上传的文件数据集
    public List<FileBean> mList;

    public ObservableField<List<UserViewInfo>> lookImgs = new ObservableField<>(new ArrayList<>());

    public CoachImgViewModel(@NonNull Application application, MyRepository model) {
        super(application, model);
    }
    //给RecyclerView添加ObservableList
    public ObservableList<CoachImgItemViewModel> contentList = new ObservableArrayList<>();

    //给RecyclerView添加ItemBinding
    public ItemBinding<CoachImgItemViewModel> contentBinding = ItemBinding.of(BR.viewModel, R.layout.item_coach_img);

    //给RecyclerView添加ObservableList
    public ObservableList<ChooseItemViewModel> fileList = new ObservableArrayList<>();

    //给RecyclerView添加ItemBinding
    public ItemBinding<ChooseItemViewModel> fileBinding = ItemBinding.of(BR.viewModel, R.layout.item_choose);

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        //查看大图
        public SingleLiveEvent<Integer> goLookImg = new SingleLiveEvent<>();
        //进入、退出编辑状态
        public SingleLiveEvent<Boolean> goEdites = new SingleLiveEvent<>();
        //进入、退出上传图片页面
        public SingleLiveEvent<Boolean> goUpdatePage = new SingleLiveEvent<>();
        //文件选取
        public SingleLiveEvent<Void> openFile = new SingleLiveEvent<>();
    }

    //进入编辑状态
    public BindingCommand goEdits = new BindingCommand(() -> {
        uc.goEdites.setValue(true);
        changeEdits(true);
    });
    //取消编辑
    public BindingCommand cancelEdits = new BindingCommand(() -> {
        uc.goEdites.setValue(false);
        changeEdits(false);
    });
    //删除照片
    public BindingCommand delectImgs = new BindingCommand(() -> {

        String ids = getIds();
        if(!BaseUtil.isValue(ids)){
            ToastUtils.showShort("请选择图片！");
            return;
        }

        setParams("ids",ids).requestData(Constants.DEL_PHOTOS);
    });
    //进入上传图片页面
    public BindingCommand goUpdatePage = new BindingCommand(() -> {
        uc.goUpdatePage.setValue(true);
    });
    //退出上传图片页面
    public BindingCommand cancelUpdate = new BindingCommand(() -> {
        uc.goUpdatePage.setValue(false);
    });

    //上传图片
    public BindingCommand release = new BindingCommand(() -> {
        if(mList != null && mList.size() > 0){
            //多文件上传
            clearFileParams().setFileParams(mList).requestData(Constants.UPFILE_OSS_MORE);
        }else{
            ToastUtils.showShort("请选择图片！");
        }
    });

    //退出上传图片页面
    public BindingCommand prompt = new BindingCommand(() -> {
        ToastUtils.showShort("不可更改");
    });

    /*
     * 拼装要删除相片的id
     * */
    private String getIds(){
        String ids = "";

        for(CoachImgItemViewModel itemModel : contentList){
            if(itemModel.entity.get().isSelect()){
                ids += ","+itemModel.entity.get().getCp_id();
            }
        }

        if(ids.length() > 0){
            return ids.substring(1);
        }else{
            return "";
        }
    }

    /*
    * 设置操作状态
    * */
    public void changeEdits(boolean flag){
        for(CoachImgItemViewModel itemModel : contentList){
            itemModel.entity.get().setEdite(flag);

            itemModel.entity.notifyChange();
        }
    }

    /*
     * 清楚某一文件
     * */
    public void deleteImg(ChooseItemViewModel itemViewModel){
        mList.remove(itemViewModel.entity);

        fileList.remove(itemViewModel);

        if(fileList.size() == 0 || (fileList.size() < 9 && fileList.get(fileList.size() - 1).entity.get().getmFile() != null)){
            addNull();
        }
    }

    /*
     * 添加一个没有值的对象
     * */
    public void addNull(){
        //添加一个空对象
        ChooseItemViewModel viewModel = new ChooseItemViewModel(this,new FileBean());
        fileList.add(viewModel);
    }

    /*
     * 添加显示对象
     * */
    public void addShow(List<LocalMedia> result){

        if(mList == null){
            mList = new ArrayList<>();
        }

        for (LocalMedia bean:result){

            if(bean.getMimeType().contains("image") && bean.isCompressed()){
                FileBean fileBean = new FileBean();
                fileBean.setFileKey("oss_file[]");
                fileBean.setFileType(bean.getMimeType());
                fileBean.setFilePath(bean.getCompressPath());
                fileBean.setFileUri(Uri.parse(bean.getCompressPath()));
                fileBean.setmFile(new File(bean.getCompressPath()));
                //添加到需要上传的文件集合里面
                mList.add(fileBean);
                //显示文件
                ChooseItemViewModel viewModel = new ChooseItemViewModel(this,fileBean);
                fileList.add(0,viewModel);

                if(fileList.size() > 9){
                    fileList.remove(9);
                }else{
                    if(fileList.get(fileList.size() - 1).entity.get().getmFile() != null){
                        addNull();
                    }
                }

            }
        }
    }

    /*
     * 拼装需要上传的图片链接
     * */
    private String getImgStr(List<ReturnMoreImgBean.FileUrlBean> myFiles){
        String urlStr = "";
        for(ReturnMoreImgBean.FileUrlBean urlBean:myFiles){
            urlStr+=","+urlBean.getOss_url();
        }
        if(urlStr.length() > 0){
            return urlStr.substring(1);
        }else{
            return "";
        }
    }

    @Override
    protected void returnData(int code, Object dataBean) {
        super.returnData(code, dataBean);

        if(code == Constants.GET_COACH_PHOTO_LIST){
            List<CoachImgBean.ListBean> list = ((CoachImgBean)dataBean).getList();
            //清除旧数据
            if(curPage == FIRST_PAGE){
                contentList.clear();
                lookImgs.get().clear();
            }

            if(list != null && list.size() > 0){
                for(CoachImgBean.ListBean bean : list){
                    CoachImgItemViewModel itemViewModel = new CoachImgItemViewModel(this,bean);
                    contentList.add(itemViewModel);
                }

                //添加图片集
                for(CoachImgBean.ListBean bean : list){
                    UserViewInfo info = new UserViewInfo(bean.getImg_src());
                    Rect bounds = new Rect();
                    info.setBounds(bounds);

                    lookImgs.get().add(info);
                }
            }

            if(contentList.size() > 0){
                if(list == null || list.size() == 0){
                    getUC().getFinishLoadMoreData().call();
                }


            }
        }

        if(code == Constants.DEL_PHOTOS){
            //删除成功，循环移除已删除项
            int delNum = contentList.size();
            for(int i = 0 ; i < delNum ; i++){

                tag:for(int j = 0 ; j < contentList.size() ; j++){
                    if(contentList.get(j).entity.get().isSelect()){
                        contentList.remove(j);
                        lookImgs.get().remove(j);
                        break tag;
                    }
                }
            }
        }

        if(code == Constants.UPFILE_OSS_MORE){
            List<ReturnMoreImgBean.FileUrlBean> myFiles = ((ReturnMoreImgBean)dataBean).getFile_url();
            //添加教练图片
            setParams("list_str",getImgStr(myFiles)).requestData(Constants.ADD_COACH_PHOTO);
        }

        if(code == Constants.ADD_COACH_PHOTO){
            curPage = FIRST_PAGE;
            requestData(Constants.GET_COACH_PHOTO_LIST);

            uc.goUpdatePage.setValue(false);

        }

    }

    /*
    * 获取当前图片的下标
    * */
    public int getPosition(ItemViewModel itemVM){
        return contentList.indexOf(itemVM);
    }
}
